<template>
  <view class="search-container">
    <navBar v-if="isShowCustomNavBar" :navbarData.sync="navbarData"></navBar>
    <tabBar :nowPages.sync="nowPages"></tabBar>

    <view class="top_search">
      <view class="search_read_only">
        <view url="" class="search_content">
          <block v-if="brandType == 2">
            <image class="search-small-icon" src="https://100000057-1252208446.cos.ap-shanghai.myqcloud.com/images/miniprogram/iocn_search.png" mode="widthFix"></image>
          </block>
          <block v-else><i class="iconfont icon-fangdajing"></i></block>
          <input class="search_input" placeholder-class="phcolor" placeholder="搜索商品" :value="keyword" confirm-type="search" @confirm="searchKeyWord" />
        </view>
      </view>
    </view>
    <!-- 客服图标 -->
    <!-- <movable-area style="width:100vw;" :style="{ height: whMovablearea }">
      <movable-view style="z-index:1000;" :x="x" :y="y" animation="false" friction="10" inertia="true" direction="all" :animation="moveAnimation"> -->
        <onlineService></onlineService>
      <!-- </movable-view> -->
      <view class="container" style="padding-bottom:100rpx">
        <!-- 如果有商品则显示 -->
        <!--三级分类-->
        <view v-if="searchError == false" :class="showThreeChild == 0 ? 'nav_wrap' : 'hideNav'">
          <view :class="isSort == 0 || isFilter > 0 ? 'nav' : 'hiddenborder'">
            <scroll-view scroll-x>
              <block v-for="(item, index) in threeChildcateList" :key="index">
                <view
                  v-if="item.visible"
                  @click="activeNav"
                  :data-index="index"
                  :data-classId="item.foreignId"
                  :data-className="item.navName"
                  :data-isSort="item.parameters.hideSort"
                  :data-isFilter="item.parameters.showFilter"
                  :data-isSpecial="item.parameters.isSpecial"
                  class="nav_item"
                  :class="index === currentIndexNav ? 'active' : ''"
                >
                  {{ item.navName }}
                </view>
              </block>
            </scroll-view>
          </view>
        </view>
        <view v-if="searchError == false">
          <filterBar
            v-if="isSort == 0 || isFilter > 0"
            :cateCode="cateCode"
            @currentType="currentType"
            @arrowType="arrowType"
            :isSort="isSort"
            :isFilter="isFilter"
            :colorFilter.sync="colorFilter"
            :materialFilter.sync="materialFilter"
            :sizeFilter.sync="sizeFilter"
            :styleFilter="styleFilter"
          ></filterBar>
        </view>
        <view v-if="list.length > 0 && searchError == false">
          <!--矩阵商品列表模块-->
          <productGridList
            ref="childItem"
            :list.sync="list"
            :listResult.sync="listResult"
            :hasMore.sync="hasMore"
            :isAppend.sync="isAppend"
            :purchasetype.sync="purchasetype"
            :finishLoadFlag.sync="finishLoadFlag"
            :categoryName.sync="categoryName"
            :groupId.sync="groupId"
            :cateCode="cateCode"
            :bannerItemsArr.sync="bannerItemsArr"
            :bannerPosition.sync="bannerPosition"
            :footerBannerPosition.sync="footerBannerPosition"
          ></productGridList>

          <!--加载更多时动画-->
          <loadMore :show.sync="showLoading" message="加载中"></loadMore>
          <!--暂无数据显示-->
          <placeholder :show.sync="is_empty" message="暂无发现数据"></placeholder>
        </view>

        <view class="history" :class="show ? '' : 'hidden'" v-else>
          <view class="doc">
            历史记录
            <span class="iconfont icon-lajitong" @click.stop="clearHis"></span>
          </view>
          <view class="lable">
            <view v-for="(item, index) in keywordhisList" :key="index" @click.stop="selHisKeyWord">
              <view class="child" :data-text="item">{{ item }}</view>
            </view>
          </view>
        </view>
        <view v-if="show == true && showhotWordList == true" class="history" :class="show ? '' : 'hidden'">
          <view class="doc">热词</view>
          <view class="lable">
            <view v-for="(item, index) in hotWordList" :key="index" @click.stop="selHisKeyWord">
              <view class="child" :data-text="item.hotword">{{ item.hotword }}</view>
            </view>
          </view>
        </view>
        <!-- 搜索错误提示 -->
        <view v-if="keyword !== ''" :class="searchError ? 'searchTip' : 'searchTipHide'">
          <text>{{ '0个结果 “' + keyword + '”' }}</text>
        </view>
      </view>
    <!-- </movable-area> -->
  </view>
</template>

<script>
import api from '@/api/api';
import tip from '@/utils/tip';
import { CART_KEY, SYSTEM_INFO, USER_SPECICAL_INFO, MERCHANT_INFO, CUSTOMER_INFO, LOWER_WX_VERSION } from '@/utils/constant';
import FilterBar from '../../components/filterBar/filterBar';
import ProductGridList from '@/components/productGridList/productGridList';
import LoadMore from '../../components/common/loadMore';
import Placeholder from '../../components/common/placeholder';
import NavBar from '../../components/common/navbar';
import onlineService from '../../components/common/onlineService';
import Loading from '../../components/common/loading';
import TabBar from '../../components/common/tabbar';
export default {
  config: {
    navigationBarTitleText: '搜索',
    navigationStyle: 'custom'
  },
  components: {
    navBar: NavBar,
    filterBar: FilterBar,
    productGridList: ProductGridList,
    loadMore: LoadMore,
    placeholder: Placeholder,
    onlineService: onlineService,
    loading: Loading,
    tabBar: TabBar
  },
  data() {
    return {
      isIpx: false,
      isShowCustomNavBar: true,
      nowPages: '',
      showLoaded: false,
      currentIndexNav: 0,
      hasMore: 0,
      finishLoadFlag: 0,
      list: [],
      identifier: 'new-items-lp',
      isIdentifier: false,
      itemsFooter: 'new-items-lp',
      preview: false,
      showList: false,
      // 色块
      frontProperties: [],
      showLoading: false,
      //防止重复加载
      preventRepeatReuqest: false,
      purchasetype: 1,
      is_empty: false,
      is_filter: false,
      //当前页面
      currentPage: 1,
      //总页数
      pageTotal: 0,
      pageSize: 16,
      keyword: '',
      hidden: true,
      searchError: false,
      keywordhisList: [],
      hotWordList: [],
      showhotWordList: true,
      hotwordVisibility: 1,
      cateCode: '',
      classId: '',
      categoryName: '',
      navId: '',
      mainNav: '', //主分类名 （一级分类名）
      // 商户id
      merchantId: '',
      show: false,
      sort: -1,
      skuval: '',
      navbarData: {
        showCapsule: 1, //是否显示左上角图标   1表示显示    0表示不显示
        navbarTitle: '搜索'
      },
      isShowList: 0,
      showThreeChild: 1,
      showChild: '', //是否显示三级分类     0显示 1不显示
      isSort: 1, //是否显示排序           0显示 1不显示
      isFilter: '', //是否显示筛选          0 不显示 1 显示
      isAppend: 0, // 是否显示悬浮图    0 不显示 1 显示
      threeChildcateList: [],
      windowHeight: 0,
      valueName: [],
      is_sort: '',
      color_filter: '',
      material_filter: '',
      size_filter: '',
      style_filter: '',
      // 全部的筛选数据
      colorFilter: [],
      materialFilter: [],
      sizeFilter: [],
      styleFilter: [],
      bannerContents: [],
      bannerItems: [],
      bannerPosition: [],
      bannerItemsArr: [],
      banners: [],
      footerBannerPosition: '',
      listResult: [],
      tempListLength: [],
      showGrid: true,
      showDesign: false,
      // 品牌信息 0：三仟院  1：ICH  2:PB
      brandType: getApp().globalData.brandType,
	  afterPage: ''
    };
  },

  onLoad(option) {
    let that = this;
    let merchantInfo = uni.getStorageSync(MERCHANT_INFO)
    this.navbarData.navbarTitle = option.title || '搜索';
    this.isIpx = getApp().globalData.isIpx;
    let pages = getCurrentPages();
    let currPage = pages[pages.length - 1];
    this.nowPages = currPage.route;
    this.list = [];
    this.skuval = '';
    this.cateCode = option.cateCode;
    this.title = option.title || '搜索';
    this.categoryName = option.title || '搜索';
    this.preview = option.preview ? option.preview : false;
    this.merchantId = uni.getStorageSync(MERCHANT_INFO).cloudMerchantId;
    this.storeId = uni.getStorageSync(MERCHANT_INFO).cloudMerchantStoreId;
    // if (this.cateCode != undefined && this.cateCode.length > 0 && this.keyword == '') { //分类进入
    //   this.show = false;
    //   this.doSearchGoods(this.cateCode, this.categoryName, this.merchantId, this.storeId, '', '', '', '', '', '');
    // } else { //搜索进入
    //   this.show = true;
    //   this.getKeyWordHisList(this.hotwordVisibility)
    // }
    // if (that.showChild == 0) {
    //   this.getChildCate(that.navId);
    // }
    that.showChild = option.showChild;
    that.isSort = option.isSort;
    that.isFilter = option.isFilter;
    that.isAppend = option.isAppend;
    that.navId = option.navId;
    that.getCurrentMerchantInfo();
    if (uni.getStorageSync('keywordhisList').length > 0) {
      this.keywordhisList = uni.getStorageSync('keywordhisList');
    }
    let systemInfo = uni.getStorageSync(SYSTEM_INFO);
    if (Number(systemInfo.SDKVersion) < Number(LOWER_WX_VERSION)) {
      this.isShowCustomNavBar = false;
    }
    this.windowHeight = systemInfo.windowHeight;
	//分类cmsbanner 位置
	this.categoryCmsBanners();
  this.getGoodsListFilter()
  },

  onShow() {
    // 刷新列表页数据
    // this.getCurrentItems()
    // //分类cmsbanner 位置
    // this.categoryCmsBanners();
  },

  methods: {
    getGoodsListFilter: async function() {
      let that = this;
      let after = that.currentPage == 1 ? '' : that.afterPage
      // getGoodsListFilter
      that.$commonFunction.getGoodsListFilter(this.cateCode, this.color_filter, this.material_filter, this.size_filter, this.style_filter).then((res) => {
        that.colorFilter = res.data.color_filter_data;
        that.materialFilter = res.data.material_filter_data;
        that.sizeFilter = res.data.size_filter_data;
        that.styleFilter = res.data.style_filter_data;
      }).catch((err) => {
        // that.showLoaded = false
        tip.plainText(err.data.msg)
      })
    },
    // 判断是否有merchantInfo,没有则重新请求
    getCurrentMerchantInfo: async function() {
      let that = this;
      var merchantInfo = uni.getStorageSync(MERCHANT_INFO) || '';
      this.merchantId = uni.getStorageSync(MERCHANT_INFO).cloudMerchantId || '';
      this.storeId = uni.getStorageSync(MERCHANT_INFO).cloudMerchantStoreId || '';
      if (merchantInfo) {
        if (this.cateCode != undefined && this.cateCode.length > 0 && this.keyword == '') {
          //分类进入
          this.show = false;
          this.doSearchGoods(this.cateCode, this.categoryName, '', '', '', '', '', '');
        } else {
          //搜索进入
          this.show = true;
          this.getKeyWordHisList(this.hotwordVisibility, this.merchantId, this.storeId);
        }

        if (that.showChild == 0) {
          this.getChildCate(that.navId, this.storeId);
        }
      } else {
        // 获取商户信息
        const accountInfo = uni.getAccountInfoSync(); // 小程序appId
        var merchantInfo = await api.merchantInfo(accountInfo.miniProgram.appId);
        if (merchantInfo.code === 200) {
          // 存储商户信息
          uni.setStorageSync(MERCHANT_INFO, merchantInfo.data);
          that.storeId = merchantInfo.data.cloudMerchantStoreId;
          that.merchantId = merchantInfo.data.cloudMerchantId;

          if (this.cateCode != undefined && this.cateCode.length > 0 && this.keyword == '') {
            //分类进入
            this.show = false;
            this.doSearchGoods(this.cateCode, this.categoryName, '', '', '', '', '', '');
          } else {
            //搜索进入
            this.show = true;
            this.getKeyWordHisList(this.hotwordVisibility, this.merchantId, this.storeId);
          }

          if (that.showChild == 0) {
            this.getChildCate(that.navId, merchantInfo.data.cloudMerchantStoreId);
          }
        }
      }
    },

    // 判断是否有merchantInfo,没有则重新请求
    getCurrentItems: async function() {
      let that = this;
      var merchantInfo = uni.getStorageSync(MERCHANT_INFO) || '';
      this.merchantId = uni.getStorageSync(MERCHANT_INFO).cloudMerchantId || '';
      this.storeId = uni.getStorageSync(MERCHANT_INFO).cloudMerchantStoreId || '';
      if (merchantInfo) {
        if (this.cateCode != undefined && this.cateCode.length > 0 && this.keyword == '') {
          //分类进入
          this.show = false;
          this.navbarData.notShowSearch = false;
          this.doSearchGoods(this.cateCode, this.categoryName, '', '', '', '');
        } else if (this.keyword) {
          //搜索进入
          this.doSearchGoods('', '', this.keyword, '', '', '', '', '');
        }
      }
    },

    // 三级分类导航数据
    getChildCate: async function(rootCateCode, storeId) {
      let merchantInfo = uni.getStorageSync(MERCHANT_INFO);
      const json = await api.merchantNavigation({
        query: {
          parent_nav_id: rootCateCode,
          store_id: storeId
        }
      });

      if (json.code === 1000) {
        // 二三级分类列表
        let childcateList = json.data.content;
        let navItems = [];
        if (childcateList.length > 0) {
          for (let i in childcateList) {
            if (childcateList[i].visible > 0) {
              navItems.push(childcateList[i]);
            }
          }
        }
        if (navItems.length > 0) {
          this.showThreeChild = 0;
          for (let i in navItems) {
            // 解析字符串为数组
            if (navItems[i]['parameters']) {
              navItems[i].parameters = JSON.parse(navItems[i]['parameters']);
            }
          }
          this.threeChildcateList = navItems;
        } else {
          this.showThreeChild = 1;
        }
      } else {
        tip.plainText(json.msg);
      }
    },

    /**
     * 搜索商品 商品列表
     */
    doSearchGoods: async function(class_id, category_name, q = '', is_sort, color_filter, material_filter, size_filter, style_filter) {
      this.isIdentifier = true;
      this.identifier = 'new-items-lp-' + class_id;
      this.itemsFooter = 'new-items-footer-lp-' + class_id;
      // 获取商品列表
      let that = this;
      let merchantInfo = uni.getStorageSync(MERCHANT_INFO)
      that.shopGridList = true;
      let after = that.currentPage == 1 ? '' : that.afterPage
        that.$commonFunction.doSearchGoods(class_id, category_name, that.currentPage, that.pageSize, after, q, is_sort, color_filter,
        material_filter, size_filter, style_filter).then((res) => {
          if (res.code === 1000) {
            that.list = [...that.list, ...res.data.content];
            if (that.currentPage == 1) {
              that.list = res.data.content;
            }
            let itemsList = res.data;
            that.colorFilter = itemsList.color_filter_data;
            that.materialFilter = itemsList.material_filter_data;
            that.sizeFilter = itemsList.size_filter_data;
            that.styleFilter = itemsList.style_filter_data;
            that.page_total = Math.ceil(res.data.total / 16);
            // 策略价格
            var s_item = [];
            for (var i in that.list) {
              s_item = that.list[i];
              var strategyIdArr = [];
              for (var j in s_item['strategies']) {
                var s_strategy = s_item['strategies'][j];
                if (
                  s_strategy['strategyStartTime'] != '' &&
                  s_strategy['strategyStartTime'] != '' &&
                  s_strategy['strategyEndTime'] != null &&
                  s_strategy['strategyEndTime'] != null &&
                  s_strategy['strategyPrice'] != null &&
                  s_strategy['strategyPrice'] != '' &&
                  Number(s_strategy['strategyPrice']) > 0
                ) {
                  var endTimestamp = Date.parse(s_strategy['strategyEndTime'].replace(/-/g, '/')); // 为了兼容IOS，需先将字符串转换为'2018/9/11 9:11:23' 返回'2018-9-12 9:11:23'的时间戳
                  var startTimestamp = Date.parse(s_strategy['strategyStartTime'].replace(/-/g, '/'));
                  var timestamp = new Date().getTime();
                  if (timestamp >= startTimestamp && timestamp < endTimestamp) {
                    strategyIdArr.push(s_strategy);
                  } else {
                  }
                }
              }
              if (strategyIdArr != '') {
                s_item['price'] = strategyIdArr[0].strategyPrice;
              }
              // let imgHeight = 346 / uni.getStorageSync('imageScaling')
              // if (!!that.list[i].hoverUrl && that.list[i].hoverUrl.indexOf('?imageView2/') == -1) {
              //   that.list[i].hoverUrl += '?imageView2/2/w/750';
              // }
              // if (that.list[i].majorUrl.indexOf('?imageView2/') == -1) {
              //   that.list[i].majorUrl += '?imageView2/2/w/750';
              // }
            }
            for (let i = 0; i < res.data.content.length; i++) {
              if(res.data.content[i].skuCodes !== undefined){
            	let enableYoushu = this.$programSetting.enableYoushu;
            	   if (enableYoushu === true) {
                   this.$sr.track('expose_sku_component', {
                   				sku: {
                   				  sku_id: res.data.content[i].skuCodes[0].toString(),
                   				  sku_name: res.data.content[i].itemName // 若商品无sku_name时，可传spu_name信息
                   				},
                   				spu: {
                   				  spu_id: !!uni.getStorageSync('openOuterItemId') ? res.data.content[i].outerItemId : res.data.content[i].itemCode.toString(),
                   				  spu_name: res.data.content[i].itemName // 若商品无spu_name时，可传sku_name信息
                   				},
                   				sku_category: [
                   				  {
                   					sku_cat_id: res.data.content[i].categoryId.toString(),
                   					sku_cat_name: '全部商品',
                   					sku_parent_cat_id: 'null' // 若已是顶级类目，传"null"
                   				  }
                   				],
                   				"shipping_shop": {
                   				  "shipping_shop_id": merchantInfo.cloudMerchantId.toString(), // 到家类型对接智慧零售入口必传
                   				  "shipping_shop_name": "THE MACALLAN EBOUTIQUE麦卡伦" // 到家类型对接智慧零售入口必传
                   				},
                   				sale: {
                   				  original_price: parseFloat(res.data.content[i].price), // 对接智慧零售入口必传
                   				  current_price: parseFloat(res.data.content[i].price) // 对接智慧零售入口必传
                   				},
                   				primary_image_url: res.data.content[i].majorUrl
                   				// more...
                   });
            	   }
              }
            }
            // 搜索错误提示
            if (q != '' && that.page_total == 0 && that.list.length < 1) {
              that.searchError = true;
            } else {
              that.searchError = false;
            }
            that.showLoaded = false;
            if (res.data.content.length < that.pageSize) {
              that.getCMSPageInfo(that.itemsFooter, that.merchantId);
            }

            //重新组合包含banner的商品列表
            that.newList();
            for (let i = 0; i < json.data.content.length; i++) {
              if (json.data.content[i].skuCodes !== undefined) {
                this.$sr.track('expose_sku_component', {
                  sku: {
                    sku_id: json.data.content[i].skuCodes[0].toString(),
                    sku_name: json.data.content[i].itemName // 若商品无sku_name时，可传spu_name信息
                  },
                  spu: {
                    spu_id: !!uni.getStorageSync('openOuterItemId') ? json.data.content[i].outerItemId : !!uni.getStorageSync('youshuOpencc') ? json.data.content[i].frontCode.toString() : json
                      .data.content[i].itemCode.toString(),
                    spu_name: !!uni.getStorageSync('youshuOpencc') ? json.data.content[i].itemName + json.data
                      .content[i].valueName : json.data.content[i].itemName // 若商品无spu_name时，可传sku_name信息
                  },
                  sku_category: [{
                    sku_cat_id: json.data.content[i].categoryId.toString(),
                    sku_cat_name: '全部商品',
                    sku_parent_cat_id: 'null' // 若已是顶级类目，传"null"
                  }],
                  "shipping_shop": {
                    "shipping_shop_id":  merchantInfo.cloudMerchantId.toString(), // 到家类型对接智慧零售入口必传
                    "shipping_shop_name": "THE MACALLAN EBOUTIQUE麦卡伦" // 到家类型对接智慧零售入口必传
                  },
                  sale: {
                    original_price: parseFloat(json.data.content[i].price), // 对接智慧零售入口必传
                    current_price: parseFloat(json.data.content[i].price) // 对接智慧零售入口必传
                  },
                  primary_image_url: json.data.content[i].majorUrl
                  // more...
                });
              }
            }
          }
        }).catch((err) => {
          that.showLoaded = false
          tip.plainText(err.data.msg)
        })
        that.showLoading = false;
        that.show = false;
        that.isShowList = 1;
      },
    //   const json = await api.getGoodsList({
    //     query: {
    //       q: q,
    //       class_id: class_id || '',
    //       page_no: that.currentPage,
    //       page_size: that.pageSize,
    //       store_id: merchantInfo.cloudMerchantStoreId,
    //       merchant_id: merchantInfo.cloudMerchantId,
    //       is_sort: is_sort,
    //       color_filter: color_filter,
    //       material_filter: material_filter,
    //       size_filter: size_filter,
    //       style_filter: style_filter
    //     }
    //   });
    //   if (json.code === 1000) {
   
    //     that.list = [...that.list, ...json.data.content];
    //     if (that.currentPage == 1) {
    //       that.list = json.data.content;
    //     }
    //     let itemsList = json.data;
    //     that.colorFilter = itemsList.color_filter_data;
    //     that.materialFilter = itemsList.material_filter_data;
    //     that.sizeFilter = itemsList.size_filter_data;
    //     that.styleFilter = itemsList.style_filter_data;
    //     that.page_total = Math.ceil(json.data.total / 16);
    //     // 策略价格
    //     var s_item = [];
    //     for (var i in that.list) {
    //       s_item = that.list[i];
    //       var strategyIdArr = [];
    //       for (var j in s_item['strategies']) {
    //         var s_strategy = s_item['strategies'][j];
    //         if (
    //           s_strategy['strategyStartTime'] != '' &&
    //           s_strategy['strategyStartTime'] != '' &&
    //           s_strategy['strategyEndTime'] != null &&
    //           s_strategy['strategyEndTime'] != null &&
    //           s_strategy['strategyPrice'] != null &&
    //           s_strategy['strategyPrice'] != '' &&
    //           Number(s_strategy['strategyPrice']) > 0
    //         ) {
    //           var endTimestamp = Date.parse(s_strategy['strategyEndTime'].replace(/-/g, '/')); // 为了兼容IOS，需先将字符串转换为'2018/9/11 9:11:23' 返回'2018-9-12 9:11:23'的时间戳
    //           var startTimestamp = Date.parse(s_strategy['strategyStartTime'].replace(/-/g, '/'));
    //           var timestamp = new Date().getTime();
    //           if (timestamp >= startTimestamp && timestamp < endTimestamp) {
    //             strategyIdArr.push(s_strategy);
    //           } else {
    //           }
    //         }
    //       }
    //       if (strategyIdArr != '') {
    //         s_item['price'] = strategyIdArr[0].strategyPrice;
    //       }
    //       // let imgHeight = 346 / uni.getStorageSync('imageScaling')
    //       // if (!!that.list[i].hoverUrl && that.list[i].hoverUrl.indexOf('?imageView2/') == -1) {
    //       //   that.list[i].hoverUrl += '?imageView2/2/w/750';
    //       // }
    //       // if (that.list[i].majorUrl.indexOf('?imageView2/') == -1) {
    //       //   that.list[i].majorUrl += '?imageView2/2/w/750';
    //       // }
    //     }
    //     // 搜索错误提示
    //     if (q != '' && that.page_total == 0 && that.list.length < 1) {
    //       that.searchError = true;
    //     } else {
    //       that.searchError = false;
    //     }
    //     that.showLoaded = false;
    //     if (json.data.content.length < that.pageSize) {
    //       that.getCMSPageInfo(that.itemsFooter, that.merchantId);
    //     }

    //     //重新组合包含banner的商品列表
    //     that.newList();
    //   } else {
    //     that.showLoaded = false;
    //     tip.plainText(json.data.msg);
    //   }
    //   that.showLoading = false;
    //   that.show = false;
    //   that.isShowList = 1;
    // },

    /**
     * @param {Object} size
     * category cmsbanner 位置判断 Begin
     */
    //分类页banner列表
    categoryCmsBanners: async function() {
      let that = this;
      const json = await api.categoryCmsBanners({
        query: {
          advertise_scene: 'LIST_PAGE',
          merchant_id: that.merchantId,
          store_id: that.storeId
        }
      });
		that.bannerPosition = [];
		that.banners = [];
		that.bannerContents = [];
		that.tempListLength = [];
      if (json.code === 200) {
        let bannerList = json.data;
		if (bannerList.length > 0) {
		            for (var i = 0; i < bannerList.length; i++) {
		              let advertiseAddtional = JSON.parse(bannerList[i].advertiseAddtional);
		              let bannerCateId = advertiseAddtional.id;
		              //只取当前分类相关banner
					if(bannerCateId == that.cateCode){
						if(that.preview){
							that.bannerContents.push(bannerList[i].bannerConfigPreview);
						}else{
							that.bannerContents.push(bannerList[i].bannerConfig);
						}
					}else if (bannerCateId.indexOf(parseInt(that.cateCode)) > -1) {
		                if(that.preview){
		                  that.bannerContents.push(bannerList[i].bannerConfigPreview);
		                }else{
		                  that.bannerContents.push(bannerList[i].bannerConfig);
		                }
		            }
		          }
				  }

        if (that.bannerContents.length > 0) {
          for (var j = 0; j < that.bannerContents.length; j++) {
            let tempBanners = JSON.parse(that.bannerContents[j]);
            that.banners.push(tempBanners);
          }

          let temBannerItems = [];
          if (that.banners.length > 0) {
            for (var i = 0; i < that.banners.length; i++) {
              for (var k = 0; k < that.banners[i].length; k++) {
                if (that.banners[i][k].contents != '') {
                  let position = that.banners[i][k].position;
                  //判断banner是否有效
                  let startTime = that.banners[i][k].startTime;

                  startTime = startTime.substring(0, 19);
                  startTime = startTime.replace(/-/g, '/');
                  let startTimeTimestamp = new Date(startTime).getTime();

                  let endTime = that.banners[i][k].endTime;
                  endTime = endTime.substring(0, 19);
                  endTime = endTime.replace(/-/g, '/');
                  let endTimeTimestamp = new Date(endTime).getTime();
                  if (startTimeTimestamp <= new Date().getTime() && new Date().getTime() < endTimeTimestamp) {
                    //当为底部banner时 position设置为10000 方便判断
                    if (position == -1) {
                      position = 10000;
                      that.footerBannerPosition = 10000;
                    }
                    that.bannerPosition.push(position);
                    for (let c in that.banners[i][k].contents) {
                      temBannerItems = JSON.parse(that.banners[i][k].contents[c].content);
                    }

                    let tempBannerContents = {
                      bannerContents: temBannerItems,
                      position: position,
                      isRow: that.banners[i][k].isRow,
                      title: that.banners[i][k].title
                    };
                    that.bannerItemsArr[position] = tempBannerContents;
                  }
                }
              }
            }
          }
        }
      }
      //重新组合包含banner的商品列表
      that.newList();
    },

    newList: async function(){
            let that = this;
            let tempList = that.list ;
            let tempBannerPosition = that.bannerPosition;
            let tempArr = [];
            // for(let i in tempList){
    		for(var i=0; i<tempList.length; i++){
    			//去重
    			for(var j=i+1; j<tempList.length; j++){
    				if(tempList[i].itemId !== undefined && tempList[j].itemId !== undefined){
    					if(tempList[i].itemId==tempList[j].itemId){         //第一个等同于第二个，splice方法删除第二个
    						tempList.splice(j,1);
    						j--;
    					}
    				}

    			}
              if(tempBannerPosition.indexOf(parseInt(i)) !== -1){
                if(that.tempListLength.indexOf(parseInt(i)) == -1){
                  var p = 0;
                  for(let b in tempBannerPosition){
                    if(tempBannerPosition[b] < i){
                      if(tempBannerPosition[b] > 1){
                        p++;
                      }
                    }
                  }

                  if(i > 1){
                    tempList.splice(parseInt(i) + p,0,that.bannerItemsArr[i]);
                  }else{
                    tempList.splice(parseInt(i) - 1,0,that.bannerItemsArr[i]);
                  }
                  tempArr.push(parseInt(i));
                }
              }
            }
            that.tempListLength = [...that.tempListLength,...tempArr];
            // that.listResult = [...that.listResult,...tempList];
            that.listResult = tempList;
            that.$forceUpdate();
          },

    /**
     * 清空历史记录
     */
    clearUserKeywords: async function() {
      this.keywordhisList = [];
      uni.removeStorageSync('keywordhisList');
    },

    /**
     * 获取热词列表
     */

    getKeyWordHisList: async function(visibility, merchantId, storeId) {
      const json = await api.searchKeywordList({
        query: {
          merchant_id: merchantId,
          store_id: storeId,
          visibility: visibility
        }
      });
      if (json.code == 1000) {
        let hotWordItems = json.data.content;
        let h_hotWort = [];
        for (let i in hotWordItems) {
          h_hotWort = hotWordItems[i];
          if (h_hotWort.visibility == 1) {
            this.hotWordList.push(h_hotWort);
          }
        }
        if (this.hotWordList.length == 0) {
          this.showhotWordList = false;
        }
      }
    },

    /**
     * 记录用户搜索热词
     */
    getUserSearchTerm: async function(searchTerm) {
      let searchUid = uni.getStorageSync('searchUid') || '';
      const json = await api.recordSearchTerm({
        method: 'POST',
        query: {
          merchantId: this.merchantId,
          searchTerm: searchTerm,
          storeId: this.storeId,
          uid: searchUid
        }
      });
    },

    /**
     * CMS配置页面
     */
    getCMSPageInfo: async function(identifier, merchantId) {
      let that = this;
      let merchantInfo = uni.getStorageSync(MERCHANT_INFO)
      let mt = '1.0';
      const json = await api.getConfigDetail({
        method: 'POST',
        query: {
          identifier: identifier,
          merchantId: merchantId || merchantInfo.cloudMerchantId,
          storeId: merchantInfo.cloudMerchantStoreId,
          mt: mt
        }
      });
      if (json.data.code === 1000 && json.data.data !== null) {
        this.hasMore = 0;
      } else {
        that.hasMore = 1;
      }
    },

    // 三级分类
    activeNav(e) {
      this.currentIndexNav = e.currentTarget.dataset.index;
      this.cateCode = e.currentTarget.dataset.classid;
      this.isFilter = e.currentTarget.dataset.isfilter;
      this.isSort = e.currentTarget.dataset.issort;
      this.isAppend = e.currentTarget.dataset.isspecial;
      this.is_sort = '';
      this.color_filter = '';
      this.material_filter = '';
      this.size_filter = '';
      this.style_filter = '';
      this.categoryName = e.currentTarget.dataset.classname;
      this.currentPage = 1;
      (this.list = []), this.doSearchGoods(this.cateCode, this.categoryName, '', '', '', '', '', '');
    },

    /**
     * 搜索
     */
    searchKeyWord: function(e) {
      this.is_sort = '';
      this.color_filter = '';
      this.material_filter = '';
      this.size_filter = '';
      this.style_filter = '';
      (this.isSort = 1), //是否显示排序
        (this.isFilter = ''), //是否显示筛选
        (this.searchError = false);
      this.showThreeChild = 1;
      this.threeChildcateList = '';
      var searchValue = e.detail.value.replace(/\s*/g, '');
      this.keyword = searchValue;
      this.categoryName = searchValue;
      if (this.cateCode == undefined && searchValue === '') {
        tip.plainText('请输入搜索词');
        return;
      } else {
        var discountName = e.detail.value['search-input'] ? e.detail.value['search-input'] : e.detail.value;
        this.list = [];
        this.currentPage = 1;
        this.is_empty = false;
        this.showLoading = false;
        this.keyword = discountName;
        if (discountName !== '') {
          if (this.keywordhisList.indexOf(discountName) < 0) {
            this.keywordhisList.push(discountName);
            uni.setStorageSync('keywordhisList', this.keywordhisList);
          }
        }
        this.storeId = uni.getStorageSync(MERCHANT_INFO).cloudMerchantStoreId;
        this.doSearchGoods('', '', this.keyword, '', '', '', '', '');
        this.getUserSearchTerm(this.keyword);
        this.$sr.track('search', {
          keyword: this.keyword
          // more...
        });
      }
    },

    //加载更多
    onReachBottom() {
      let that = this;
      that.merchantId = uni.getStorageSync(MERCHANT_INFO).cloudMerchantId;
      that.storeId = uni.getStorageSync(MERCHANT_INFO).cloudMerchantStoreId;
      that.showLoading = false;
      //判断总页数是否大于翻页数
      if (that.page_total > that.currentPage) {
        //防止重复加载
        if (that.preventRepeatReuqest) {
          return true;
        }
        that.preventRepeatReuqest = true;
        that.currentPage++;
        let classId = '';
        if (this.cateCode != undefined) {
          classId = this.cateCode;
        }
        if (classId != '' || this.keyword != '') {
          that.doSearchGoods(classId, '', this.keyword, this.is_sort, this.color_filter, this.material_filter, this.size_filter, this.style_filter);
        }
        that.preventRepeatReuqest = false;
      } else {
        that.showLoading = false;
      }
    },
    // 按排序显示商品列表
    currentType(obj) {
      this.list = [];
      this.currentPage = 1;
      this.is_sort = obj.is_sort;
      this.is_empty = false;
      this.show = false;
      this.doSearchGoods(this.cateCode, '', this.keyword, this.is_sort, this.color_filter, this.material_filter, this.size_filter, this.style_filter);
    },

    // 按筛选条件排序
    arrowType(obj) {
      this.color_filter = obj.color_filter;
      this.material_filter = obj.material_filter;
      this.size_filter = obj.size_filter;
      this.style_filter = obj.style_filter;
      this.list = [];
      this.currentPage = 1;
      this.doSearchGoods(this.cateCode, '', this.keyword, this.is_sort, this.color_filter, this.material_filter, this.size_filter, this.style_filter);
    },

    /**
     * 热词和历史记录的搜索
     */
    selHisKeyWord(e) {
      this.list = [];
      this.currentPage = 1;
      var discountName = e.target.dataset.text;
      this.showLoading = true;
      this.keyword = discountName.replace(/\s*/g, '');
      if (discountName !== '') {
        if (this.keywordhisList.indexOf(discountName) < 0) {
          this.keywordhisList.push(discountName);
          uni.setStorageSync('keywordhisList', this.keywordhisList);
        }
      }
      this.$sr.track('search', {
        keyword: this.keyword
        // more...
      });
      this.storeId = uni.getStorageSync(MERCHANT_INFO).cloudMerchantStoreId;
      this.doSearchGoods('', '', this.keyword, '', '', '', '', '');
      this.getUserSearchTerm(this.keyword);
    },

    clearHis() {
      this.clearUserKeywords();
    },
    onShareAppMessage: function(res) {
      if (res.from === 'button') {
        // 来自页面内转发按钮
      }else{
        this.$EFSTracking.trackingAction('SHARE_CARD', res.from, {});
      }
      let imageUrl = ''
      let path = '/pages/item/categoryNew?cateCode=' + this.cateCode + '&title=' + this.title
      let title = uni.getStorageSync('storeName') || '小程序商城'
      this.$commonSensors.sensorsPageShare();
			this.$sr.setContext({ share_title: title });
      return this.$commonFunction.commonShare(res, title, path, imageUrl)
    },
    onShareTimeline() {
			let title = uni.getStorageSync('storeName') || '小程序商城'
			this.$sr.setContext({ share_title: title });
      return {
        title: uni.getStorageSync('storeName') || '小程序商城',
        query: 'cateCode=' + this.cateCode + '&title=' + this.title
      }
    }
  }
};
</script>

<style lang="less">
.history {
  padding: 40rpx 30rpx 0;
}

.doc {
  font-size: 30rpx;
}

.lable {
  margin-top: 20rpx;
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  margin-left: -20rpx;

  .child {
    background: #dedede;
    padding: 10rpx 20rpx;
    border-radius: 300rpx;
    margin-left: 20rpx;
    font-size: 26rpx;
    margin-top: 5rpx;
    color: #000;
    margin-bottom: 15rpx;
  }
}

.content {
  display: none;
}

.search_read_only .search_content {
  width: 100%;
}

.search_input {
  margin-left: 10rpx;
  padding: 4px 11px 4px 0;
}

.search_read_only .search_content {
  border-radius: 0;
  padding: 0 0 5px;
  background: none;
  border-bottom: 1px solid #e7e7e7;
}

.search_read_only {
  padding: 0;
  margin: 0 24rpx 16rpx;
  width: auto;
}

.search-suggestions {
  padding: 30rpx 80rpx;
  display: block;
}

.btn_box .btn_2 {
  border: 1px solid #e7e7e7;
  background-color: #fff;
  margin-top: 40rpx;
  color: #444;
}

.icon-lajitong {
  font-size: 30rpx;
  float: right;
}

.icon-search {
  margin-top: -4px;
}

.icon-fangdajing {
  font-size: 36rpx;
  margin-top: -1px;
}

.phcolor {
  color: #ccc;
}

.fix-iphonex-button::after {
  content: ' ';
  position: fixed;
  bottom: 0 !important;
  height: auto !important;
  width: 100%;
  background: #fff;
}

.nav_wrap {
  color: #999;
  padding: 0 20rpx;
}

.hideNav {
  display: none;
}

.nav {
  white-space: nowrap;
  padding-bottom: 11rpx;
  overflow-x: auto;
  border-bottom: 1px solid #e7e7e7;
}

.hiddenborder {
  white-space: nowrap;
  padding-bottom: 11rpx;
  overflow-x: auto;
}

.nav_item {
  padding: 20rpx 45rpx 20rpx 0;
  display: inline-block;
  color: #999;
}

.nav_item.active {
  color: #444;
}

.searchTip {
  width: 100%;
  height: 100%;
  padding: 40rpx 0 0 20rpx;
  letter-spacing: 0.04em;
  font-size: 26rpx;
  background: #fff;
  color: #444;
}

.searchTipHide {
  display: none;
}
.search-container .icon-wap-home,
.search-container .navbar-v-line {
  display: none;
}
.search-small-icon {
  width: 40rpx;
  height: 40rpx;
  margin-bottom: 4px;
}
</style>
